package Modulo4;

import Acceso.Security;
import Modelo.DAL.Personal_DAO;
import Modelo.PersonalDsi;
import Modelo.PerteneceGrupo;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.json.JSONObject;

/**
 *
 * @author Alberto Sanchez
 */

/*
 * Metodo que valida que una cadena tenga u formato determinado
 * @param cadena: String a validar
 * @param type: Tipo de patron a validar (1=caracteres simples, 2=numeros, 3=caracteres, 4=email)
 * @return boolean
 */
public class consultarPersonalAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    public boolean validatePattern(String cadena, int type) {
        Matcher m;
        Pattern p;
        switch (type) {
            case 1:
                p = Pattern.compile("[a-zA-Z]+");
                break;
            case 2:
                p = Pattern.compile("[0-9]*");
                break;
            case 3:
                p = Pattern.compile("[a-zA-Záéíóú ]*");
                break;
            case 4:
                p = Pattern.compile("^([0-9a-zA-Z]([_.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+([a-zA-Z]{2,9}.)+[a-zA-Z]{2,3})$");
                break;
            default:
                return false;
        }

        m = p.matcher(cadena);
        return m.matches();
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        String[] a = {"Administrador", "Director DSI", "Jefe Apoyo Administrativo", "Personal Administrativo"};
        if (!Security.validateSession(request, a)) {
            return mapping.findForward("errorPriv");
        }

        ActionErrors errors = new ActionErrors();

        String voe = request.getParameter("voe").trim();
        String ci = request.getParameter("ci").trim();
        String usbid = request.getParameter("usbid").trim();
        String nombre1 = request.getParameter("nombre1").trim();
        String apellido1 = request.getParameter("apellido1").trim();
        String grupo = request.getParameter("grupo");

        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String order = request.getParameter("order");
        String asc = request.getParameter("asc");


        boolean hayError = false;

        //Comprueba que el campo cedula solo tenga numeros
        if (ci != null && !ci.equals("")) {
            if (!validatePattern(ci, 2)) {
                errors.add("invalid_Cedula", new ActionMessage("errors.invalid_Cedula"));
                saveErrors(request, errors);
                hayError = true;
            } else {
                ci = voe + "-" + ci;
            }
        }

        if (usbid.length() > 1 && !validatePattern(usbid, 2)) {
            errors.add("invalid_UsbId", new ActionMessage("errors.invalid_UsbId"));
            saveErrors(request, errors);
            hayError = true;
        }
        if (!validatePattern(nombre1, 3)) {
            errors.add("invalid_caracter_N1", new ActionMessage("errors.invalid_caracter_N1"));
            saveErrors(request, errors);
            hayError = true;
        }
        if (!validatePattern(nombre1, 3)) {
            errors.add("invalid_caracter_N2", new ActionMessage("errors.invalid_caracter_N2"));
            saveErrors(request, errors);
            hayError = true;
        }
        if (!validatePattern(nombre1, 3)) {
            errors.add("invalid_caracter_A1", new ActionMessage("errors.invalid_caracter_A1"));
            saveErrors(request, errors);
            hayError = true;
        }
        if (!validatePattern(nombre1, 3)) {
            errors.add("invalid_caracter_A2", new ActionMessage("errors.invalid_caracter_A2"));
            saveErrors(request, errors);
            hayError = true;
        }

        if (hayError) {
            errors.add("No_hay_Resultados", new ActionMessage("errors.No_hay_Resultados"));
            saveErrors(request, errors);
            return mapping.findForward(FAILURE);
        }

        PersonalDsi pDsi = new PersonalDsi();
        pDsi.setCi(ci);
        pDsi.setUsbid(usbid);
        pDsi.setNombre1(nombre1);
        pDsi.setApellido1(apellido1);
        pDsi.setUsbid(usbid);

        PerteneceGrupo pg = new PerteneceGrupo();
        pg.setIdGrupo(grupo);
        
        response.setContentType("text/json");

        JSONObject personas = Personal_DAO.consultarEmpleados(pDsi, pg, limit, offset, order, asc);
        PrintWriter pw = response.getWriter();
        pw.write(personas.toString());
        pw.flush();
        pw.close();

        return mapping.findForward(SUCCESS);
    }
}
